﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using System.ComponentModel;
using System.Threading;
using System.Windows.Media.Animation;
using NAudio.MediaFoundation;
using NAudio.Wave;

namespace JapaneseMusicHtmlCreator
{
    /// <summary>
    /// PagePreview.xaml 的交互逻辑
    /// </summary>
    public partial class PageCreateAndSave : Page
    {
        public BackgroundWorker createHtmlWorker = null;
        private MainWindow mainWindow;
        public bool thisPage = false;
        public double lastValue;




        public PageCreateAndSave(MainWindow mainWindow)
        {
            // TODO: Complete member initialization
            InitializeComponent();
            this.mainWindow = mainWindow;
          
          
            
        }

       

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            SaveMemory();
        }

        private void btnPrev_Click(object sender, RoutedEventArgs e)
        {
            SaveMemory();
            mainWindow.NavigateBackward(this, mainWindow.pageSettings);
        }

        private void SaveMemory()
        {
          
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
        
           
        }

        private void btnSelectDir_Click(object sender, RoutedEventArgs e)
        {

            FolderBrowserDialog ofd = new FolderBrowserDialog();
            
            ofd.SelectedPath = Environment.CurrentDirectory;
          
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                mainWindow.createDir = ofd.SelectedPath+"\\"+mainWindow.musicArtist+"-"+mainWindow.musicTitle;
                string[] s=ofd.SelectedPath.Split('\\');
                tbCreateDir.Text = s[s.Length - 1] + "\\" + mainWindow.musicArtist + "-" + mainWindow.musicTitle;
                tbCreateDir.Focus();
                tbCreateDir.Select(tbCreateDir.Text.Length, 0);
            }
        }

        private void btnCreateHtml_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(mainWindow.createDir))
            {
                if (!Directory.Exists(mainWindow.createDir))
                {
                    Directory.CreateDirectory(mainWindow.createDir);
                }
                createHtmlWorker = new BackgroundWorker();
                createHtmlWorker.DoWork += createHtmlWorker_DoWork;
                createHtmlWorker.RunWorkerCompleted += createHtmlWorker_RunWorkerCompleted;
                createHtmlWorker.WorkerReportsProgress = true;
                createHtmlWorker.ProgressChanged += createHtmlWorker_ProgressChanged;
                createHtmlWorker.RunWorkerAsync();
                btnCreateHtml.IsEnabled = false;
              
            }
            else
            {
                System.Windows.MessageBox.Show("请选择目录", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        void createHtmlWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ProgressBarAnimate(lastValue, e.ProgressPercentage);
            lastValue = e.ProgressPercentage;
        }

        private void ProgressBarAnimate(double lastValue, double value)
        {
            DoubleAnimation d = new DoubleAnimation(lastValue, value, TimeSpan.FromMilliseconds(200));
            pbCreateProgress.BeginAnimation(System.Windows.Controls.ProgressBar.ValueProperty, d);
        }

        void createHtmlWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnCreateHtml.IsEnabled = true;
        }

        void createHtmlWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            CreateFiles();
            
        }

        private void CreateFiles()
        {
            createHtmlWorker.ReportProgress(0);
            Thread.Sleep(200); 
            createHtmlWorker.ReportProgress(50);
            CreateMusic();
            Thread.Sleep(100);
            createHtmlWorker.ReportProgress(60);
            CreateBackground();
            Thread.Sleep(200);           
            createHtmlWorker.ReportProgress(80); 
            CreateHtml();
            Thread.Sleep(100);           
            createHtmlWorker.ReportProgress(90);CreateCss();
            Thread.Sleep(100);
            createHtmlWorker.ReportProgress(100);
            CreateJavaScript();

        }

        private void CreateJavaScript()
        {
            using (FileStream fs = new FileStream(mainWindow.createDir + @"\script.js", FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    string s = "";
                    if (mainWindow.musicLineAnimeTime == 0)
                    {
                        s += "var animetime=500;\r\n";
                    }
                    else
                    {
                        s += "var animetime=" + mainWindow.musicLineAnimeTime + ";\r\n";
                    }
                    if (!string.IsNullOrEmpty(mainWindow.musicBkgndPath))
                    {
                        s += "var bImgHori=true;\r\n";
                    }
                    else
                    {
                        s += "var bImgHori=false;\r\n";
                    }
                    if (!string.IsNullOrEmpty(mainWindow.musicBkgndPath2))
                    {
                        s += "var bImgVert=true;\r\n";
                    }
                    else
                    {
                        s += "var bImgVert=false;\r\n";
                    }
                  
                    s +=
@"var audio=null;
var timer=null;
var lastid=-1;
var bScroll=false;
var from=null;
var to=null;
var player=null;
var scrollx=null;
var bShowPlayer=false;
var audioheight=null;
var bLoad=false;
var bMouseState=false;
var bUseVert=false;
var imgBkgnd=null;
var timerInterval=25;
function load() {
    imgBkgnd=document.getElementsByClassName('background')[0];
    audio=document.getElementsByClassName('audio')[0];
    holders=document.getElementsByClassName('holder');
    player=document.getElementsByClassName('player')[0];
    audioheight=audio.offsetHeight+'px';
    player.style.display='none';
    selectPic();
    audio.play();
    bLoad=true;
    timer=setInterval(action,timerInterval);
}
function selectPic(){
    if(imgBkgnd!=null&&imgBkgnd!==undefined){
        bUseVert = window.innerWidth < window.innerHeight;
        if(!bUseVert){
            if(bImgHori){
                imgBkgnd.style.display='block';
                imgBkgnd.src='background.jpg';
            }else{
                imgBkgnd.style.display='none';
            }  
        }else{
            if(bImgVert){
                imgBkgnd.style.display='block';
                imgBkgnd.src='background2.jpg';
            }else{
                imgBkgnd.style.display='none';
            }  
        }
    }  
}
function mousedown(){
   bMouseState=true;
}
function mouseup(){
    if(bMouseState) {
        if (bLoad) {
            if (!bShowPlayer) {
                bShowPlayer = true;
                player.style.height = audioheight;
                player.style.display = 'block';
            } else {
                bShowPlayer = false;
                player.style.display = 'none';
            }
        }
    }
    bMouseState=false;
}
function action() {
    var currenttime=audio.currentTime;
    var temp=Math.round(currenttime*100);
    var id=getCurrentID(holders,temp);
    if(id!==lastid) {
        clearClass(holders);
        if(id!==-1) {
            var holdercontent = document.getElementById(id.toString()).getElementsByTagName('div');
            var kashi = holdercontent[0];
            var translate = holdercontent[1];
            kashi.className='kashi animate kashicurrent';
            translate.className='translate animate translatecurrent';
            bScroll=true;
            scrollCount=0;
            from = window.scrollY;
            to = kashi.offsetTop - window.innerHeight / 2 + kashi.offsetHeight / 2;
            scrollx=window.scrollX;
        }
    }
    lastid=id;
    if(bScroll){
        scrollCount++;
        scrollTo(scrollx, from + (to - from) * scrollCount*timerInterval / animetime);
        if(scrollCount>=animetime/timerInterval){
            bScroll=false;
        }
    }
}
function getCurrentID(holders,temp) {
    var k=-1;
    for(var i=0;i<holders.length;i++){
        var t=parseInt(holders[i].id);
        if(temp>t){
            k=t;
        }
    }
    return k;
}
function clearClass(holders) {
    for(var i=0;i<holders.length;i++) {
        var holdercontent = holders[i].getElementsByTagName('div');
        var kashi = holdercontent[0];
        var translate = holdercontent[1];
        kashi.className = 'kashi animate';
        translate.className = 'translate animate';
    }
}
function resize(){
    selectPic();
}";
                    sw.Write(s);
                }
            }
        }

        private void CreateCss()
        {
            using (FileStream fs = new FileStream(mainWindow.createDir + @"\style.css", FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    string s = "";
                    s += AddClassS("body");
                    s += AddClassP("margin", "0");
                    s += AddClassP("background-color", ConvertColorToHtml(mainWindow.musicBackgroundColor));
                    s += AddClassE();

                    s += AddClassS("body::-webkit-scrollbar");
                    s += AddClassP("display", "none");
                    s += AddClassE();
              
                    s += AddClassS("player");
                    s += AddClassP("width", "100%");
                    s += AddClassP("display", "block");
                    s += AddClassP("position", "fixed");
                    s += AddClassP("bottom", "0");
                    s += AddClassE();
                    s += AddClassS("audio");
                    s += AddClassP("width", "100%");
                    s += AddClassE();


                    s += AddClassS("title");
                    if (mainWindow.musicTitleFontSize == 0)
                    {
                        s += AddClassP("font-size", "90px");
                    }
                    else 
                    {
                        s += AddClassP("font-size", (int)(mainWindow.musicTitleFontSize) + "px");
                    }
                    s += AddClassP("color", ConvertColorToHtml(mainWindow.musicTitleColor));
                    s += AddClassP("margin", "0 30% 0 0");
                    s += AddClassP("text-align", "center");
                    s += AddClassE();
                    s += AddClassS("artist");
                    if (mainWindow.musicArtistFontSize == 0)
                    {
                        s += AddClassP("font-size", "65px");
                    }
                    else
                    {
                        s += AddClassP("font-size", (int)(mainWindow.musicArtistFontSize) + "px");
                    }
                    s += AddClassP("color", ConvertColorToHtml(mainWindow.musicArtistColor));
                    s += AddClassP("margin", "0 0 0 30%");
                    s += AddClassP("text-align", "center");
                    s += AddClassE();
                    s += AddClassS("kashi");
                    if (mainWindow.musicLineFontSize == 0)
                    {
                        s += AddClassP("font-size", "42px");
                    }
                    else
                    {
                        s += AddClassP("font-size", (int)(mainWindow.musicLineFontSize) + "px");
                    }
                    s += AddClassP("color", ConvertColorToHtml(mainWindow.musicKashiColor));
                    //if (mainWindow.musicLineAnimeTime == 0)
                    //{
                    //    s += AddClassP("transition", "500ms");

                    //}
                    //else
                    //{
                    //    s += AddClassP("transition", (int)mainWindow.musicLineAnimeTime+"ms");
                    //}  
                    s += AddClassE();

                    s += AddClassS("translate");
                    if (mainWindow.musicLineFontSize == 0)
                    {
                        s += AddClassP("font-size", "34px");
                    }
                    else
                    {
                        int temp = (int)(mainWindow.musicLineFontSize) - 8;
                        if (temp < 0) temp = 0;
                        s += AddClassP("font-size", temp + "px");
                    }
                    s += AddClassP("color", ConvertColorToHtml(mainWindow.musicTranslateColor));
                    
                    s += AddClassE();

                    s += AddClassS("kashicurrent");
                    if (mainWindow.musicCurrentLineFontSize == 0)
                    {
                        s += AddClassP("font-size", "48px");
                    }
                    else
                    {
                        s += AddClassP("font-size", (int)(mainWindow.musicCurrentLineFontSize) + "px");
                    }
                    s += AddClassP("color", ConvertColorToHtml(mainWindow.musicCurrentKashiColor));
                    s += AddClassE();

                    s += AddClassS("translatecurrent");
                    if (mainWindow.musicCurrentLineFontSize == 0)
                    {
                        s += AddClassP("font-size", "40px");
                    }
                    else
                    {
                        int temp = (int)(mainWindow.musicCurrentLineFontSize) - 8;
                        if (temp < 0) temp = 0;
                        s += AddClassP("font-size", temp + "px");
                    }
                    s += AddClassE();
                   
                   
                    s += AddClassS("kana");
                    s += AddClassP("color", ConvertColorToHtml(mainWindow.musicKanaColor));
                    s += AddClassE();

                    s += AddClassS("content");
                    s += AddClassP("width", "100%");
                    s += AddClassP("height", "100%");
                    s += AddClassE();

                    s += AddClassS("holder");
                    s += AddClassP("text-align", "center");
                    s += AddClassE();

                    s += AddClassS("background");
                    s += AddClassP("z-index", "-1");
                    s += AddClassP("width", "100%");
                    s += AddClassP("height", "100%");
                    s += AddClassP("position", "fixed");
                    s += AddClassE();
                    s += AddClassS("animate");
                    if (mainWindow.musicLineAnimeTime == 0)
                    {
                        s += AddClassP("transition", "500ms");

                    }
                    else
                    {
                        s += AddClassP("transition", (int)mainWindow.musicLineAnimeTime + "ms");
                    }
                    s += AddClassE();
                    sw.Write(s);
                        
                }
            }
        }

        private string ConvertColorToHtml(Color color)
        {
            byte r, g, b;
            r = color.R;
            g = color.G;
            b = color.B;
            return "#" + ColorHex(r) + ColorHex(g) + ColorHex(b);
        }

        private string ColorHex(byte b)
        {
            string p = "0123456789ABCDEF";
            string s = "";
            s += p[b / 16];
            s += p[b % 16];
            return s;
        }

        private string AddClassP(string p1, string p2)
        {
            return "\t" + p1 + ":" + p2 + ";\r\n";
        }

        private string AddClassE()
        {
            return "}\r\n";
        }

        private string AddClassS(string p)
        {
            return "." + p + "{\r\n";
        }

        private void CreateHtml()
        {
            using (FileStream fs = new FileStream(mainWindow.createDir + @"\page.html", FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    string s = "";
                    s += AddDocType();
                    s += AddTagS0("html");
                    s += AddTagS0("head");

                    s += AddTagS1("meta", "charset", "UTF-8");
                    s += AddTagS32("link", "type", "text/css", "rel", "stylesheet", "href", "style.css");
                    s += AddTagS2("script", "type", "text/javascript", "src", "script.js") + AddTagE("script");
                    s += AddTitle(mainWindow.musicArtist, mainWindow.musicTitle);
                    s += AddTagE("head");
                    s += AddTagS5("body", "class", "body","onload","load()","onmousedown","mousedown()","onmouseup","mouseup()","onresize","resize()");
                    s += AddTagS1("div", "class", "player");
                    s += AddAudio();
                    s += AddTagE("div");
                    s += AddTagS1("div", "class", "content");
                    if (!string.IsNullOrEmpty(mainWindow.musicBkgndPath))
                    {
                        s += AddTagS12("img", "class", "background");
                    }
                    s += AddTagS1("div", "class", "title");
                    s += mainWindow.musicTitle + AddLineRtn();
                    s += AddTagE("div");
                    s += AddTagS1("div", "class", "artist");
                    s += mainWindow.musicArtist + AddLineRtn();
                    s += AddTagE("div");
                    s += AddBodyContent();
                    s += AddTagE("div");
                    s += AddTagE("body");
                    s += AddTagE("html");
                    sw.Write(s);

                }
            }
        }

        private string AddBodyContent()
        {
            string ret = "<br/>";
            try
            {
                string[] kashis = mainWindow.musicKashi.Split('\n');
                for (int i = 0; i < kashis.Length; i++)
                {
                    ret += ConvertKashi(kashis[i]);
                }
                ret += "<br/>" + AddLineRtn();
            }
            catch
            {
                return "歌词中存在错误，请检查！";
            }
            return ret;
        }

        private string ConvertKashi(string p)
        {
            if (!string.IsNullOrEmpty(p))
            {
                int id = int.Parse(p.Substring(1, 2)) * 6000 + int.Parse(p.Substring(4, 2)) * 100 + int.Parse(p.Substring(7, 2));
                string content = p.Substring(10, p.Length - 10);
                string kashi = "";
                string trans = "";
                string ret = "";
                string[] temp = content.Split('@');
                if (temp.Length > 1)
                {
                    kashi = temp[0];
                    if (!string.IsNullOrWhiteSpace(temp[1]))
                        trans = temp[1];
                    else
                        trans = "<br/>";
                }
                else
                {
                    kashi = temp[0];
                    trans = "<br/>";
                }
                ret += AddTagS2("div", "class", "holder", "id", id.ToString());
                ret += AddTagS1("div", "class", "kashi");
                bool kanjiFlag = false;
                for (int i = 0; i < kashi.Length; i++)
                {
                    if (kashi[i] != '#' && kashi[i] != '$')
                    {
                        ret += kashi[i];
                    }
                    else if (kashi[i] == '$' && !kanjiFlag)
                    {
                        kanjiFlag = true;
                        ret += "<ruby>";
                    }
                    else if (kashi[i] == '$' && kanjiFlag)
                    {
                        ret += "<rp>(</rp><rt><span class=\"kana\">";
                    }
                    else if (kashi[i] == '#' && kanjiFlag)
                    {
                        kanjiFlag = false;
                        ret += "</span></rt><rp>)</rp></ruby>";
                    }

                }
                ret += AddLineRtn();
                ret += AddTagE("div");
                ret += AddTagS1("div", "class", "translate");
                ret += trans + AddLineRtn();
                ret += AddTagE("div");
                ret += AddTagE("div") + "<br/>" + AddLineRtn();

                return ret;
            }
            return "";
        }

       
        private string AddAudio()
        {
            return "<audio class=\"audio\" controls>" + AddLineRtn() + "<source src=\"music.mp3\"/>" + AddLineRtn() + "</audio>" + AddLineRtn();
        }
        private string AddTitle(string p1, string p2)
        {
            return AddTagS0("title") + p1 + "-" + p2 +AddLineRtn()+ AddTagE("title");
        }

        private string AddTagS1(string tag, string p1, string v1)
        {
            return "<" + tag + " " + p1 + "=\"" + v1 + "\">" + AddLineRtn();
        }
        private string AddTagS12(string tag, string p1, string v1)
        {
            return "<" + tag + " " + p1 + "=\"" + v1 + "\"/>" + AddLineRtn();
        }
        private string AddTagS2(string tag, string p1, string v1,string p2,string v2)
        {
            return "<" + tag + " " + p1 + "=\"" + v1 + "\" " + p2 + "=\"" + v2 + "\">" + AddLineRtn();
        }
        private string AddTagS22(string tag, string p1, string v1, string p2, string v2)
        {
            return "<" + tag + " " + p1 + "=\"" + v1 + "\" " + p2 + "=\"" + v2 + "\"/>" + AddLineRtn();
        }
        private string AddTagS3(string tag, string p1, string v1, string p2, string v2,string p3,string v3)
        {
            return "<" + tag + " " + p1 + "=\"" + v1 + "\" " + p2 + "=\"" + v2 + "\" " + p3 + "=\"" + v3 + "\">" + AddLineRtn();
        }
        private string AddTagS32(string tag, string p1, string v1, string p2, string v2, string p3, string v3)
        {
            return "<" + tag + " " + p1 + "=\"" + v1 + "\" " + p2 + "=\"" + v2 + "\" " + p3 + "=\"" + v3 + "\"/>" + AddLineRtn();
        }
        private string AddTagS4(string tag, string p1, string v1, string p2, string v2, string p3, string v3,string p4,string v4)
        {
            return "<" + tag + " " + p1 + "=\"" + v1 + "\" " + p2 + "=\"" + v2 + "\" " + p3 + "=\"" + v3 + "\" " + p4 + "=\"" + v4 + "\">" + AddLineRtn();
        }
        private string AddTagS5(string tag, string p1, string v1, string p2, string v2, string p3, string v3, string p4, string v4,string p5,string v5)
        {
            return "<" + tag + " " + p1 + "=\"" + v1 + "\" " + p2 + "=\"" + v2 + "\" " + p3 + "=\"" + v3 + "\" " + p4 + "=\"" + v4 + "\" " + p5 + "=\"" + v5 + "\">" + AddLineRtn();
        }
        private string AddDocType()
        {
            return "<!DOCTYPE html>" + AddLineRtn();
       
        }
        private string AddLineRtn()
        {
            return "\r\n";
        }
        private string AddTagS0(string tag)
        {
            return "<" + tag + ">" + AddLineRtn(); 
        }
        private string AddTagE(string tag)
        {
            return "</" + tag + ">" + AddLineRtn();
        }
        private void CreateBackground()
        {
            if (mainWindow.musicBkgndPath != null)
            {
                WriteableBitmap bitmap = new WriteableBitmap(new BitmapImage(new Uri(mainWindow.musicBkgndPath, UriKind.Absolute)));
                Int32Rect rect = new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight);
                int stride = bitmap.Format.BitsPerPixel * rect.Width / 8;
                byte[] data = new byte[rect.Height * stride];
                bitmap.CopyPixels(rect, data, stride, 0);
                for (int i = 0; i < rect.Height * rect.Width; i++)
                {
                    if (mainWindow.musicBkgndUseBlack)
                    {
                        byte b = data[i * 4];
                        data[i * 4] = (byte)(b * (100 - mainWindow.musicBkgndValue) / 100);
                        b = data[i * 4 + 1];
                        data[i * 4 + 1] = (byte)(b * (100 - mainWindow.musicBkgndValue) / 100);
                        b = data[i * 4 + 2];
                        data[i * 4 + 2] = (byte)(b * (100 - mainWindow.musicBkgndValue) / 100);
                    }
                    else
                    {
                        byte b = data[i * 4];
                        data[i * 4] = (byte)((255 - b) * mainWindow.musicBkgndValue / 100 + b);
                        b = data[i * 4 + 1];
                        data[i * 4 + 1] = (byte)((255 - b) * mainWindow.musicBkgndValue / 100 + b);
                        b = data[i * 4 + 2];
                        data[i * 4 + 2] = (byte)((255 - b) * mainWindow.musicBkgndValue / 100 + b);
                    }

                }
                bitmap.WritePixels(rect, data, stride, 0);
                BitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmap));

                using (var fileStream = new System.IO.FileStream(mainWindow.createDir + @"\background.jpg", System.IO.FileMode.Create))
                {
                    encoder.Save(fileStream);
                }
            }
            if (mainWindow.musicBkgndPath2 != null)
            {
                WriteableBitmap bitmap = new WriteableBitmap(new BitmapImage(new Uri(mainWindow.musicBkgndPath2, UriKind.Absolute)));
                Int32Rect rect = new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight);
                int stride = bitmap.Format.BitsPerPixel * rect.Width / 8;
                byte[] data = new byte[rect.Height * stride];
                bitmap.CopyPixels(rect, data, stride, 0);
                for (int i = 0; i < rect.Height * rect.Width; i++)
                {
                    if (mainWindow.musicBkgndUseBlack)
                    {
                        byte b = data[i * 4];
                        data[i * 4] = (byte)(b * (100 - mainWindow.musicBkgndValue) / 100);
                        b = data[i * 4 + 1];
                        data[i * 4 + 1] = (byte)(b * (100 - mainWindow.musicBkgndValue) / 100);
                        b = data[i * 4 + 2];
                        data[i * 4 + 2] = (byte)(b * (100 - mainWindow.musicBkgndValue) / 100);
                    }
                    else
                    {
                        byte b = data[i * 4];
                        data[i * 4] = (byte)((255 - b) * mainWindow.musicBkgndValue / 100 + b);
                        b = data[i * 4 + 1];
                        data[i * 4 + 1] = (byte)((255 - b) * mainWindow.musicBkgndValue / 100 + b);
                        b = data[i * 4 + 2];
                        data[i * 4 + 2] = (byte)((255 - b) * mainWindow.musicBkgndValue / 100 + b);
                    }

                }
                bitmap.WritePixels(rect, data, stride, 0);
                BitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmap));

                using (var fileStream = new System.IO.FileStream(mainWindow.createDir + @"\background2.jpg", System.IO.FileMode.Create))
                {
                    encoder.Save(fileStream);
                }
            }
        }

        private void CreateMusic()
        {
            //try
            //{
            //    File.Copy(mainWindow.musicPath, mainWindow.createDir + @"\music." + mainWindow.musicType, true);
            //}
            //catch (IOException ignored) { }
            string type=mainWindow.musicType.ToUpper();
            string tempfile=System.IO.Path.GetTempFileName();
            if(type.Equals("MP3")){
                using (var reader = new Mp3FileReader(mainWindow.musicPath))
                {
                    WaveFileWriter.CreateWaveFile(tempfile,reader);
                }
            }
            else
            {
                tempfile = mainWindow.musicPath;
            }
            MediaFoundationApi.Startup();
            var t = MediaFoundationEncoder.SelectMediaType(
                    AudioSubtypes.MFAudioFormat_MP3,
                    new WaveFormat(44100, 1),
                    192000);
            if (t != null)
            {
                using (var reader = new WaveFileReader(tempfile))
                {
                    using (var enc = new MediaFoundationEncoder(t))
                    {
                        try
                        {
                            enc.Encode(mainWindow.createDir + @"\music.mp3", reader);
                        }
                        catch
                        {

                        }
                    }
                   
                } 
            }

            
        }

        private void btnPreview_Click(object sender, RoutedEventArgs e)
        {
            string path = mainWindow.createDir + @"\page.html";
            if (File.Exists(path))
            {
                System.Diagnostics.Process.Start(path);
            }
        }

        private void btnSaveJmh_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter= "jmh 文件|*.jmh";
            DialogResult res=sfd.ShowDialog();
            if (res == DialogResult.OK)
            {
                SaveJmh(sfd.FileName);
            }
        }

        private void SaveJmh(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                using (BinaryWriter writer = new BinaryWriter(fs))
                {
                    char[] temp = new char[100];
                    mainWindow.musicTitle.CopyTo(0, temp, 0, mainWindow.musicTitle.Length);
                    writer.Write(temp);
                    temp = new char[100];
                    mainWindow.musicArtist.CopyTo(0, temp, 0, mainWindow.musicArtist.Length);
                    writer.Write(temp);
                    temp = new char[1000];
                    mainWindow.musicPath.CopyTo(0, temp, 0, mainWindow.musicPath.Length);
                    writer.Write(temp);
                    temp = new char[1000];
                    if (!string.IsNullOrEmpty(mainWindow.musicBkgndPath))
                        mainWindow.musicBkgndPath.CopyTo(0, temp, 0, mainWindow.musicBkgndPath.Length);
                    writer.Write(temp);
                    temp = new char[1000];
                    if (!string.IsNullOrEmpty(mainWindow.musicBkgndPath2))
                        mainWindow.musicBkgndPath2.CopyTo(0, temp, 0, mainWindow.musicBkgndPath2.Length);
                    writer.Write(temp);
                    temp = new char[10000];
                    if (!string.IsNullOrEmpty(mainWindow.musicKashi))
                        mainWindow.musicKashi.CopyTo(0, temp, 0, mainWindow.musicKashi.Length);
                    writer.Write(temp);
                    writer.Write(mainWindow.musicBkgndValue);
                    writer.Write(mainWindow.musicBkgndUseBlack);
                    writer.Write(mainWindow.musicKashiColor.ToString());
                    writer.Write(mainWindow.musicTranslateColor.ToString());
                    writer.Write(mainWindow.musicKanaColor.ToString());
                    writer.Write(mainWindow.musicCurrentKashiColor.ToString());
                    writer.Write(mainWindow.musicTitleColor.ToString());
                    writer.Write(mainWindow.musicArtistColor.ToString());
                    writer.Write(mainWindow.musicBackgroundColor.ToString());
                    writer.Write(mainWindow.musicLineFontSize);
                    writer.Write(mainWindow.musicCurrentLineFontSize);
                    writer.Write(mainWindow.musicLineAnimeTime);
                    writer.Write(mainWindow.musicTitleFontSize);
                    writer.Write(mainWindow.musicArtistFontSize);
                    

                }
            }

            System.Windows.MessageBox.Show("保存成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            
        }

        
    }
}
